<template>
  <div class="p-6">
    <h2 class="text-2xl font-bold mb-4">后台管理</h2>

    <el-tabs v-model="activeTab">
      <!-- 菜品管理 -->
      <el-tab-pane label="菜品管理" name="foods">
        <div class="mb-4 flex justify-between">
          <div></div>
          <el-button type="primary" @click="openFoodDialog()">新增菜品</el-button>
        </div>

        <el-table :data="foods" border stripe>
          <el-table-column prop="foodId" label="ID" width="80" />
          <el-table-column prop="foodName" label="菜名" />
          <el-table-column prop="foodPrice" label="价格(元)" width="120" />
          <el-table-column prop="foodCategory" label="分类" width="120" />
          <el-table-column prop="foodCount" label="库存剩余" width="120" />
          <!-- 新增状态列 -->
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.foodStatus === 'onsale' ? 'success' : 'danger'">
                {{ row.foodStatus === 'onsale' ? '已上架' : '已下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <el-button size="small" @click="openFoodDialog(row)">编辑</el-button>
              <!-- 将删除按钮替换为上下架切换按钮 -->
              <el-button 
                size="small" 
                :type="row.foodStatus === 'onsale' ? 'warning' : 'success'"
                @click="updateFoodStatus(row.foodId, row.foodStatus === 'onsale' ? 'notsale' : 'onsale')"
              >
                {{ row.foodStatus === 'onsale' ? '下架' : '上架' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 菜品分页 -->
        <div class="mt-4 flex justify-center">
          <el-pagination
            v-model:current-page="foodPage.currentPage"
            v-model:page-size="foodPage.pageSize"
            :total="foodPage.total"
            layout="prev, pager, next, jumper"
            @current-change="handleFoodPageChange"
            @size-change="handleFoodSizeChange"
          />
        </div>
      </el-tab-pane>

      <!-- 订单管理 -->
      <el-tab-pane label="订单管理" name="orders">
        <el-table :data="orders" border stripe>
          <el-table-column prop="orderlistId" label="订单ID" width="100" />
          <el-table-column prop="userId" label="用户ID" width="100" />
          <el-table-column prop="orderlistPrice" label="总价(元)" width="120" />
          <el-table-column label="状态" width="150">
            <template #default="{ row }">
              <el-select
                v-model="row.orderlistStatus"
                placeholder="选择状态"
                size="small"
                @change="updateOrder(row)"
              >
                <el-option label="未支付" value="未支付" />
                <el-option label="已支付" value="已支付" />
                <el-option label="已完成" value="已完成" />
                <el-option label="已取消" value="已取消" />
                <el-option label="制作中" value="制作中" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="创建时间">
            <template #default="{ row }">
              {{ formatChinaTime(row.orderlistTime) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 订单分页 -->
        <div class="mt-4 flex justify-center">
          <el-pagination
            v-model:current-page="orderPage.currentPage"
            v-model:page-size="orderPage.pageSize"
            :total="orderPage.total"
            layout="prev, pager, next, jumper"
            @current-change="handleOrderPageChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 菜品弹窗 -->
    <el-dialog v-model="foodDialogVisible" title="菜品信息">
      <el-form :model="foodForm" label-width="80px">
        <el-form-item label="菜名">
          <el-input v-model="foodForm.foodName" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="foodForm.foodPrice" type="number" />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="foodForm.foodCategory" />
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model="foodForm.foodCount" type="number" />
        </el-form-item>
        <!-- 新增状态选择 -->
        <el-form-item label="状态">
          <el-radio-group v-model="foodForm.foodStatus">
            <el-radio label="onsale">上架</el-radio>
            <el-radio label="notsale">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="foodDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveFood">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { get, post } from '../utils/axios.js'
// 新增导入ElMessageBox用于库存预警弹窗
import { ElMessage, ElMessageBox } from 'element-plus'

// Tabs
const activeTab = ref('foods')

// 分页参数
const foodPage = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const orderPage = reactive({
  currentPage: 1,
  pageSize: 15,
  total: 0
})

// 菜品管理
const foods = ref([])
const foodDialogVisible = ref(false)
const foodForm = reactive({
  foodId: null,
  foodName: '',
  foodPrice: 0,
  foodCategory: '',
  foodCount: 0,
  foodStatus: 'onsale'
})

function openFoodDialog(food = null) {
  if (food) {
    Object.assign(foodForm, food)
  } else {
    Object.assign(foodForm, {
      foodId: null,
      foodName: '',
      foodPrice: 0,
      foodCategory: '',
      foodCount: 0,
      foodStatus: 'onsale'
    })
  }
  foodDialogVisible.value = true
}

async function saveFood() {
  try {
    let res
    if (foodForm.foodId) {
      res = await post('/food/update', foodForm)
      if (res === 'success') ElMessage.success('修改成功')
      else ElMessage.error('修改失败')
    } else {
      res = await post('/food/add', foodForm)
      if (res === 'success') ElMessage.success('新增成功')
      else ElMessage.error('新增失败')
    }
    foodDialogVisible.value = false
    loadFoods()
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

// 更新菜品状态（上下架）
async function updateFoodStatus(foodId, status) {
  try {
    const res = await post('/food/status', {}, {
      params: { foodId, foodStatus: status }
    })
    if (res === 1) {
      ElMessage.success(status === 'onsale' ? '上架成功' : '下架成功')
      loadFoods()
    } else {
      ElMessage.error(status === 'onsale' ? '上架失败' : '下架失败')
    }
  } catch (err) {
    console.error('状态更新错误:', err)
    const errorMsg = err.response?.data?.message || err.message || '状态更新失败'
    ElMessage.error(`操作失败: ${errorMsg}`)
  }
}

// 新增：检测库存低于20的菜品并弹窗提示
function checkLowStock() {
  // 筛选库存<20的菜品（转换为数字避免字符串比较错误）
  const lowStockFoods = foods.value.filter(
    (food) => Number(food.foodCount) < 20
  )

  // 若存在低库存菜品，生成弹窗内容并提示
  if (lowStockFoods.length > 0) {
    // 构造带换行的提示内容（用HTML实现换行）
    const warningContent = lowStockFoods
      .map((food) => `- ${food.foodName}：剩余${food.foodCount}份`)
      .join('<br>')

    // 弹窗展示库存预警
    ElMessageBox.alert(
      `<div class="font-medium">以下菜品库存不足20份，请及时补货：</div>
       <div style="margin-top: 12px; color: #666;">${warningContent}</div>`,
      '库存预警',
      {
        type: 'warning', // 警告类型（黄色图标）
        dangerouslyUseHTMLString: true, // 允许解析HTML（实现换行）
        confirmButtonText: '知道了',
        confirmButtonClass: 'el-button--warning'
      }
    )
  }
}

// 加载菜品（分页）- 新增调用checkLowStock检测库存
async function loadFoods() {
  try {
    const res = await get('/food/menu', {
      page: foodPage.currentPage,
      size: foodPage.pageSize
    })
    foods.value = res.records || []
    foodPage.total = res.total || 0
    // 菜品数据加载完成后，检测低库存并弹窗
    checkLowStock()
  } catch (err) {
    console.error(err)
    ElMessage.error('加载菜品失败')
  }
}

function handleFoodPageChange(page) {
  foodPage.currentPage = page
  loadFoods()
}
function handleFoodSizeChange(size) {
  foodPage.pageSize = size
  foodPage.currentPage = 1
  loadFoods()
}

// 订单管理
const orders = ref([])

async function loadOrders() {
  try {
    const storeId = localStorage.getItem('storeId')
    if (!storeId) {
      ElMessage.error('未找到所属店铺')
      return
    }
    const res = await get('/orderlist/all', {
      storeId,
      page: orderPage.currentPage,
      size: orderPage.pageSize
    })
    orders.value = res.records || []
    orderPage.total = res.total || 0
  } catch (err) {
    console.error(err)
    ElMessage.error('加载订单失败')
  }
}

async function updateOrder(order) {
  try {
    const res = await get('/orderlist/updateStatus', {
      orderlistId: order.orderlistId,
      orderlistStatus: order.orderlistStatus
    })
    if (res === 'success') {
      ElMessage.success('状态已更新')
      loadOrders()
    } else {
      ElMessage.error('更新失败')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('更新失败')
  }
}

function handleOrderPageChange(page) {
  orderPage.currentPage = page
  loadOrders()
}

// 格式化时间
function formatChinaTime(timeStr) {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

/* ---------  SSE 实时更新 --------- */
let es = null
let reconnectTimer = null
let retryDelay = 2000

function setupSSE() {
  cleanupSSE()
  es = new EventSource('/food/stream')

  es.addEventListener('connected', () => {
    console.log('Admin SSE 已连接')
  })

  es.addEventListener('message', (evt) => {
    try {
      const payload = JSON.parse(evt.data || '{}')
      if (payload.type === 'foodStatus') {
        applyFoodStatusUpdate(payload)
      }
    } catch (e) {
      console.warn('SSE parse error:', e)
    }
  })

  es.onerror = () => {
    console.warn('Admin SSE 断开，重连中...')
    cleanupSSE()
    clearTimeout(reconnectTimer)
    reconnectTimer = setTimeout(setupSSE, retryDelay)
  }
}

function cleanupSSE() {
  if (es) {
    es.close?.()
    es = null
  }
}

function applyFoodStatusUpdate({ foodId, foodStatus }) {
  const idx = foods.value.findIndex(i => i.foodId === foodId)
  if (idx !== -1) {
    foods.value[idx].foodStatus = foodStatus
  }
}

onMounted(() => {
  loadFoods() // 页面初始化加载菜品，触发库存检测
  loadOrders()
  setupSSE()
})

onBeforeUnmount(() => {
  cleanupSSE()
  clearTimeout(reconnectTimer)
})
</script>

<style scoped>
.p-6 {
  padding: 1.5rem;
}
</style>